import './styles/element-variables.scss'
import './assets/font/iconfont.css'
import Vue from 'vue'
import router from './router'
import App from './App'
import store from './store'
import ElementUI from 'element-ui'
import {NetUtil} from './utils/NetUtil'
import {addDevice, WebSocketConfig} from "./utils/WebsocketConfig";
import mqtt from './browserMqtt';
import {ipcRenderer, remote} from 'electron'
import {mutations_const} from "./config/StoreConstant";
import {DongleConfig} from "./config/DongleConfig";

require('./assets/font/iconfont');
Vue.use(ElementUI);
Vue.config.productionTip = false;

NetUtil.updToken()
    .then(() => {
        new Vue({
            components: {App},
            router,
            store,
            template: '<App/>',
            created() {
                window.vueMain = this
            },
            beforeCreate() {


                let mqttServer = "ws://192.168.1.237:8083/mqtt";
                // mqttServer = "ws://120.79.148.202:8083/mqtt";
                //mqttServer = "wss://mqtttcp.hongchentech.com/wssmqtt";
                //mqttServer = "wss://mqtttcp.hongchentech.com/mqtt";
                mqttServer = "wss://mqtttcp.hongchenpen.com/mqtt";

                window.client = mqtt.connect(mqttServer) // you add a ws:// url here

            }
        }).$mount('#app')
    });
let delay = 0;

remote.process.argv.forEach((value) => {

    if (value.indexOf('-donotshow') !== -1) delay = DongleConfig.startUpDelay;
});

/** 初始化websocket 信息  **/
setTimeout(() => {
    let wsUrl = 'ws://localhost:5678';

    let heartCheck = {
        timeout: 100 * 1000,  //  心跳检测时长
        timeoutObj: null, // 定时变量
        reset: function () { // 重置定时
            clearTimeout(this.timeoutObj);
            return this;
        },
        start: function () { // 开启定时
            this.timeoutObj = setTimeout(function () {
                // 心跳时间内收不到消息，主动触发连接关闭，开始重连
                window.ws.close();
            }, this.timeout)
        }
    };
    let dongleStatus = 1;

    function initEventHandle() {

        function setOffDevice() {

            window.ws.send(JSON.stringify({cmd: 0x60}))
        }

        function setOnDevice() {

            window.ws.send(JSON.stringify({cmd: 0x20, para: vueMain.$store.getters.deviceMacList}));
        }

        function getOfflineData() {

            window.ws.send(JSON.stringify({cmd: 0x09, para: 0x01}));
        }

        window.ws.onclose = function () {
            ipcRenderer.removeListener('setOffDevice', setOffDevice);
            ipcRenderer.removeListener('setOnDevice', setOnDevice);
            ipcRenderer.removeListener('getOfflineData', getOfflineData);
            if (dongleStatus === 2) {
                ipcRenderer.send('resetDongle');
                store.commit(mutations_const.UPD_HAS_ADD_DEVICE, 1);
                dongleStatus = 1;
            }
            console.info('ws_on_close');
            reconnect(wsUrl);
        };
        window.ws.onerror = function (err) {
            console.info(err);
            ipcRenderer.removeListener('setOffDevice', setOffDevice);
            ipcRenderer.removeListener('setOnDevice', setOnDevice);
            ipcRenderer.removeListener('getOfflineData', getOfflineData);
            ipcRenderer.send('resetDongle');
            store.commit(mutations_const.UPD_HAS_ADD_DEVICE, 1);
            dongleStatus = 1;
            reconnect(wsUrl);
        };
        window.ws.onopen = function () {
            dongleStatus = 2;
            heartCheck.reset().start();      //心跳检测重置
            if (store.state.Member.hasLogin) {
                addDevice();
            }
            ipcRenderer.send('connectSuccess');
            ipcRenderer.on('setOffDevice', setOffDevice);
            ipcRenderer.on('setOnDevice', setOnDevice);
            ipcRenderer.on('getOfflineData', getOfflineData);
        };
        window.ws.onmessage = function (res) {    //如果获取到消息，心跳检测重置
            heartCheck.reset().start();      //拿到任何消息都说明当前连接是正常的
            let data = JSON.parse(res.data);
            let f = WebSocketConfig.getHandle(data.cmd);
            if (f) {
                f(data)
            }
        };
    }

    function createWebSocket(url) {
        try {
            window.ws = new WebSocket(url);
            initEventHandle();
        } catch (e) {
            reconnect(url);
        }
    }

    function reconnect(url) {
        if (reconnect.lockReconnect) return;
        reconnect.lockReconnect = true;
        setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
            createWebSocket(url);
            reconnect.lockReconnect = false;
        }, 8000);
    }

    createWebSocket(wsUrl);
}, 2000 + delay / 20
);
